import {createRouter, createWebHashHistory, Router} from 'vue-router';
import {constantRoute} from './routes'
import {removeDynamicRouter} from  '@/utils'
import NProgress from "nprogress";
import "nprogress/nprogress.css";
//获取用户相关的小仓库内部token数据,去判断用户是否登录成功
import useUserStore from '@/store/modules/user'
import pinia from '@/store'

const userStore = useUserStore(pinia)


let router: Router = createRouter({
    //路由模式hash
    history: createWebHashHistory(),
    routes: constantRoute,
    //滚动行为
    scrollBehavior() {
        return {
            left: 0,
            top: 0
        }
    }
})

export let asyncRoute: any[] = []

const importModules = import.meta.glob('./modules/*.ts', {eager: true})
// console.log(importModules);

for (const path in importModules) {
    const routerModule: any = importModules[path]
    asyncRoute = [
        ...asyncRoute,
        ...(routerModule.default || routerModule)
    ]
}
// console.log(asyncRoute);

//全局守卫:项目当中任意路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to: any, _: any, next: any) => {
    document.title = `${import.meta.env.VITE_APP_TITLE}-${to.meta.title}`
    NProgress.start();
    //to:你将要访问那个路由
    //from:你从来个路由而来
    //next:路由的放行函数

    // 获取token,去判断用户登录、还是未登录
    const token = userStore.token
    //获取用户名字
    let username: string = userStore.username;
    // 用户登录判断
    if (token) {
        //登录成功,访问login,不能访问,指向首页
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            //登录成功访问其余六个路由(登录排除)
            // 有用户信息
            if (!username) {
                try {
                    await userStore.getUserInfo();
                    //万一刷新的时候是异步路由，有可能获取用户信息，异步路由还没有加载完毕，出现空白的效果
                    next({...to})
                } catch (e) {
                    removeDynamicRouter(router)
                    await userStore.userLogout()
                    next({path: '/login', query: {redirect: to.path}})
                }
            } else {
                next()
            }
        }
    } else {
        //用户未登录判断
        if (to.path == '/login') {
            next()
        } else {
            next({path: '/login', query: {redirect: to.path}})
        }
    }
})

//全局后置守卫
router.afterEach(() => {
    NProgress.done()
});

export default router;
